﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

namespace GetCarInfo
{
    class HtmlTag
    {
        private String m_Name;
        private String m_BeginTag;
        private String m_InnerHTML;
        private Hashtable m_Attributes = new Hashtable();

        static Regex attrReg = new Regex(@"([a-zA-Z1-9_-]+)\s*=\s*(\x27|\x22)([^\x27\x22]*)(\x27|\x22)", RegexOptions.IgnoreCase);

        private HtmlTag(string name, string beginTag, string innerHTML)
        {
            m_Name = name;
            m_BeginTag = beginTag;
            m_InnerHTML = innerHTML;

            MatchCollection matchs = attrReg.Matches(beginTag);
            foreach (Match match in matchs)
            {
                m_Attributes[match.Groups[1].Value.ToUpper()] = match.Groups[3].Value;
            }
        }

        public List<HtmlTag> FindTag(String name)
        {
            return FindTag(m_InnerHTML, name, String.Format(@"<{0}(\s[^<>]*|)>", name));
        }

        public List<HtmlTag> FindTag(String name, String format)
        {
            return FindTag(m_InnerHTML, name, format);
        }

        public List<HtmlTag> FindTagByAttr(String tagName, String attrName, String attrValue)
        {
            return FindTagByAttr(m_InnerHTML, tagName, attrName, attrValue);
        }

        public String TagName
        {
            get { return m_Name; }
        }

        public String InnerHTML
        {
            get { return m_InnerHTML; }
        }

        public String GetAttribute(string name)
        {
            return m_Attributes[name.ToUpper()] as String;
        }

        public static String GetHtml(string url)
        {
            //WebProxy wp = new WebProxy("210.13.114.200", true);
            //wp.Credentials = new NetworkCredential("i-tingrs", "");
            HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
            //req.Proxy = wp;
            req.Timeout = 30 * 1000;
            HttpWebResponse response = req.GetResponse() as HttpWebResponse;
            Stream stream = response.GetResponseStream();

            MemoryStream buffer = new MemoryStream();
            Byte[] temp = new Byte[4096];
            int count = 0;
            while ((count = stream.Read(temp, 0, 4096)) > 0)
            {
                buffer.Write(temp, 0, count);
            }

            return Encoding.GetEncoding(response.CharacterSet).GetString(buffer.GetBuffer());
        }

        /// <summary>
        /// 在文本html的文本查找标志名为tagName,并且属性attrName的值为attrValue的所有标志
        /// 例如：FindTagByAttr(html, "div", "class", "demo")
        /// 返回所有class为demo的div标志
        /// </summary>
        public static List<HtmlTag> FindTagByAttr(String html, String tagName, String attrName, String attrValue)
        {
            String format = String.Format(@"<{0}\s[^<>]*{1}\s*=\s*(\x27|\x22){2}(\x27|\x22)[^<>]*>", tagName, attrName, attrValue);
            return FindTag(html, tagName, format);
        }

        public static List<HtmlTag> FindTag(String html, String name, String format)
        {
            Regex reg = new Regex(format, RegexOptions.IgnoreCase);
            Regex tagReg = new Regex(String.Format(@"<(\/|)({0})(\s[^<>]*|)>", name), RegexOptions.IgnoreCase);
            List<HtmlTag> tags = new List<HtmlTag>();
            int start = 0;
            while (true)
            {
                Match match = reg.Match(html, start);
                if (match.Success)
                {
                    start = match.Index + match.Length;
                    Match tagMatch = null;
                    int beginTagCount = 1;

                    while (true)
                    {
                        tagMatch = tagReg.Match(html, start);
                        if (!tagMatch.Success)
                        {
                            tagMatch = null;
                            break;
                        }
                        start = tagMatch.Index + tagMatch.Length;
                        if (tagMatch.Groups[1].Value == "/") beginTagCount--;
                        else beginTagCount++;
                        if (beginTagCount == 0) break;
                    }

                    if (tagMatch != null)
                    {
                        HtmlTag tag = new HtmlTag(name, match.Value, html.Substring(match.Index + match.Length, tagMatch.Index - match.Index - match.Length));
                        tags.Add(tag);
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            return tags;
        }

        public static string OneorTwo(string str)
        {
            string url = "";
            string one = str.Substring(10);
            int two = one.IndexOf("\"");
            string three = one.Substring(0, two);
            url = three;
            return url;
        }
    }
}
